package com.weige.conver.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.weige.conver.entity.DeviceDTO;
import com.weige.conver.entity.DeviceInfo;
import com.weige.conver.entity.ResultInfo;
import com.weige.conver.utils.RedisUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/device")
public class DeviceController {


    @Autowired
    private RedisUtils redisUtils;

    @RequestMapping("/getDevices")
    @ResponseBody
    public ResultInfo<List<DeviceDTO>> getDeviceData(Integer page, Integer limit){
        List<String> list = redisUtils.getByHash("device");
        List<DeviceDTO> deviceInfoList = new ArrayList<>();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (String data : list){
            DeviceInfo deviceInfo =  JSON.parseObject(data,new TypeReference<DeviceInfo>(){});
            DeviceDTO deviceDTO = new DeviceDTO();
            BeanUtils.copyProperties(deviceInfo,deviceDTO);
            deviceDTO.setOnlineTime(sdf.format(new Date(deviceInfo.getOnlineTime())));
            deviceInfoList.add(deviceDTO);
        }
        int devicelength = deviceInfoList.size();
        int start = (page-1)*limit;
        int end = (page*limit)-1;
        if (end > devicelength){
            end = devicelength;
        }
        List<DeviceDTO> dtoList = deviceInfoList.subList(start,end);
        return new ResultInfo<>(dtoList,deviceInfoList.size());
    }
}
